package com.nccsjz.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.catalina.Session;

import com.nccsjz.front.service.IndexCardService;
import com.nccsjz.pojo.Vote;
import com.nccsjz.pojo.VoteAnswer;

import utils.FileUtils;

public class WebContentFilter implements Filter {

	public WebContentFilter() {
	}

	@Override
	public void destroy() {

	}

	@SuppressWarnings("deprecation")
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
//		System.out.println("is Called .........");
		HttpServletResponse resp = (HttpServletResponse) response;
		HttpServletRequest requ = (HttpServletRequest) request;
		requ.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		String realPath = requ.getRealPath("");
		String servletPath = requ.getServletPath().replace("/","\\");
		String filePath = realPath + servletPath;
//		 System.out.println("realPath:"+requ.getRealPath("")+"\n tttt:"+requ.getServletPath());
//		 System.out.println(filePath);
//		 System.out.println("servletPath:"+servletPath);


		// 开始替换HTML的登录和投票部分 ，注意:读取和写入都要UTF-8字符集
		if (requ.getServletPath().contains("html")&&servletPath.split("\\\\").length==3&&!servletPath.contains("back")) {
			PrintWriter out = response.getWriter();
			BufferedReader br = new BufferedReader(new FileReader(filePath));
			String tem = null;
			tem=FileUtils.readFromFile(filePath);
//			while ((tem = br.readLine()) != null) {
//				tem=new String(tem.getBytes("gbk"),"utf-8");
				
				// 登录部分
				if (tem.contains("${logContent}")) {
//					System.out.println("ccc:"+tem);
					HttpSession session = this.getSession(requ);
					// 用户已经登录
					if (null != session.getAttribute("smname")) {
						// 卡户
						if (Integer.parseInt(session.getAttribute("st")
								.toString()) == 1) {
							tem = tem.replace("${logContent}", this
									.getReplace(realPath).split("##")[1]);
						}
						// 商户
						if (Integer.parseInt(session.getAttribute("st")
								.toString()) == 2) {
							tem = tem.replace("${logContent}", this
									.getReplace(realPath).split("##")[2]);
						}
						tem = tem.replace("${smname}", session.getAttribute(
								"smname").toString());
						tem = tem.replace("${sid}", session.getAttribute("sid")
								.toString());

					} else {
						// 用户没有登录
						tem = tem.replace("${logContent}", "");
					}
				}
				
				//替换投票相关
				try {
					tem = tem.replace("${vote}", getVoteStr());
				} catch (Exception e) {
					e.printStackTrace();
				}
				System.out.println(tem);
//				for(int i=0;i<tem.length();i++){
//					out.write(tem);
//					out.println(tem.charAt(i));
//				}
				
//				out.write(new String(tem.getBytes("gbk"),"utf-8"));
//			}
			out.println(tem);
			out.flush();
			out.close();
		}

		chain.doFilter(request, response);

	}

	public static void main(String[] arg){
//		String tem="我是中国ABC河北aa";
//		System.out.println(tem.length());
//		System.out.println("...................");
//		for(int i=0;i<tem.getBytes().length;i++){
//		System.out.println(i+":"+tem.getBytes()[i]);
//		}
//		System.out.println("...................");
//		System.out.println(tem.getBytes().length);
		
		System.out.println(File.separator);
		System.out.println(File.separatorChar);
		System.out.println(File.pathSeparator);
		System.out.println(File.separator);
	}
	public HttpSession getSession(HttpServletRequest request) {
		return request.getSession();
	}

	/**
	 * 读取用于替换的字符
	 * 
	 * @param path
	 * @return
	 * @throws IOException
	 */
	public String getReplace(String path) throws IOException {
		String tempFile = path + "/" + "common/tempStr";

		return FileUtils.readFromFile(tempFile);
	}

	/**
	 * 用户投票相关
	 * 
	 * @return
	 * @throws Exception
	 */
	public String getVoteStr() throws Exception {
		Vote vo = new IndexCardService().getSelectedVote();
		String temp="";
		if(null!=vo){
			temp = "<span class=gg>问题：" + vo.getTitle() + "</span><br>";
			String str = "";
			for (VoteAnswer va : vo.getAnswers()) {
				str = str
						+ "<input style='border: 0' name=answerid  type=checkbox value="
						+ va.getVoteAnswerId() + " /><span class=gg >"
						+ va.getContent() + "</span><br> ";
			}
			temp = temp + str;
		}
		
		return temp;
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}

}
